﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class Backend_RolesList : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ShowRolesToGridview();
        }
    }

    public void ShowRolesToGridview()
    {
        grvRolesList.DataSource = Roles.GetAllRoles();
        grvRolesList.DataBind();
    }

    protected void btnCreateRole_Click(object sender, EventArgs e)
    {
        String roleNew = txtRoleNew.Text.Trim();
        if (!Roles.RoleExists(roleNew))
        {
            try
            {
                Roles.CreateRole(roleNew);
                lblMessage.Text = "Tạo quyền mới thành công.";
                ShowRolesToGridview();
            }
            catch (Exception)
            {
                lblMessage.Text = "Đã có lỗi xảy ra khi thêm quyền mới.";
            }
        }
        else
        {
            lblMessage.Text = "Quyền này đã tồn tại. Bạn hãy tạo quyền mới khác.";
        }
    }
    protected void grvRolesList_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        Label RoleNameLabel = grvRolesList.Rows[e.RowIndex].FindControl("lblRoleName") as Label;
        Roles.DeleteRole(RoleNameLabel.Text, false);
        ShowRolesToGridview();
    }

    public void ShowUserFormRoles(string roleName)
    {
        string[] usersBelongingToRole = Roles.GetUsersInRole(roleName);

        RolesUserList.DataSource = usersBelongingToRole;
        RolesUserList.DataBind();
    }
    protected void grvRolesList_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        Label RoleNameLabel = grvRolesList.Rows[e.NewSelectedIndex].FindControl("lblRoleName") as Label;
        ShowUserFormRoles(RoleNameLabel.Text);
        lblRoleName.Text = RoleNameLabel.Text;
        mtvUserInRole.ActiveViewIndex = 0;
        
    }
    protected void RolesUserList_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string selectedRoleName = lblRoleName.Text;
        // Reference the UserNameLabel
        Label UserNameLabel = RolesUserList.Rows[e.RowIndex].FindControl("UserNameLabel") as Label;
        // Remove the user from the role
        Roles.RemoveUserFromRole(UserNameLabel.Text, selectedRoleName);
        // Refresh the GridView
        ShowUserFormRoles(lblRoleName.Text);
    }
}